package com.tscnd.core.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.tscnd.core.entity.role.Role;
import com.tscnd.core.entity.user.User;
import com.tscnd.core.service.role.IRoleService;
import com.tscnd.core.service.user.IUserService;
import com.tscnd.core.utils.EncryptTools;
import com.tscnd.core.utils.SysContextUtil;
import com.tscnd.core.constant.Constants;


@SuppressWarnings("deprecation")
public class UserDetailsServiceImpl implements UserDetailsService {
	@Autowired
	private IUserService userService;
	@Autowired
	private IRoleService roleService;
	
	public static final String LOCKED = "1";
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException
	{
		//注意UsernameNotFoundException 异常 提示的都是 坏的凭证
		User myUser = null;
		try
		{
			System.out.println(username);
			myUser = userService.findByUsersLogin(username);
			
		} catch (Exception e)
		{
			e.printStackTrace();	
			throw new UsernameNotFoundException(username);
			
		}
		if (myUser == null)
		{
			throw new UsernameNotFoundException(username);
		} else{
			if (LOCKED.equals(myUser.getAcNonLocked()))
			{
				throw new LockedException("该用户处于锁定状态");
			}
		}
		//由于没有使用Spring Security加密策略
		//自定义加密策略
		HttpServletRequest request= SysContextUtil.getRequest();
		String validateCode=(String) request.getSession().getAttribute(Constants.S_VALIDATE_CODE);
		String password=myUser.getPassword();
		password = EncryptTools.MD5(EncryptTools.MD5(password+username,32)+validateCode,32);
		myUser.setPassword(password);
		
		
		Collection<GrantedAuthority> authorities = obtionGrantedAuthorities(myUser);
		boolean enabled = true;  
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;  
        boolean accountNonLocked = true;
        
		org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
				myUser.getUsername(), myUser.getPassword(), enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, authorities);
		return user;
	}
	
	/**
	 * 根据用户 查询出所属所有的权限（角色的权限）
	 * @param users
	 * @return
	 */
	private Set<GrantedAuthority> obtionGrantedAuthorities(User myUser)
	{
		Set<GrantedAuthority> authsSet = new HashSet<GrantedAuthority>();
		try
		{
			Set<Role>roleSet=roleService.findUserByRole(myUser.getUsername());
			for (Role role : roleSet)
			{
				authsSet.add(new GrantedAuthorityImpl(role.getAuthorityMark()));
			}
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return authsSet;
	}
}
